#! /usr/bin/env python
# -*- coding: utf-8 -*-


from web.form.bootstrap import BootStrap
from web import models
from django import forms
from django.core.exceptions import ValidationError
# 自定义样式
from web.form.widgets import ColorRadioSelect


class ProjectModelForm(BootStrap, forms.ModelForm):
    # color 不在应用bootstap样式
    bootstrap_class_exclude = ['color']

    # desc = forms.CharField(widget=forms.Textarea())

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']

        widgets = {
            'desc': forms.Textarea(),
            'color': ColorRadioSelect(attrs={'class': 'color-radio'}),
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        """
        项目效验
        1. 当前用户是否已创建
        2. 是否有额度创建
        :return:
        """
        name = self.cleaned_data['name']
        exist = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exist:
            raise ValidationError('项目名已存在')

        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限')

        return name


